#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include "packet.h"
#include "group_command.h"
int default_time_ms = 50;
void output_head_info(packet_head_t *head)
{
    printf("destid:%02x packet_len:%02x srcid:%02x\n", head->remoteid, head->packet_len,
           head->localid);
}
bool checksum_packet(uint8_t *data, int len)
{
    int sum = 0;
    for (int i = 0; i < len; i++)
    {
        sum += data[i];
    }
    if (sum % 256 == 0)
    {
        return true;
    }
    return false;
}
void output_data(const char *text, uint8_t *data, int len)
{
    printf("%s len:%d =>", text, len);
    for (int i = 0; i < len; i++)
    {
        printf("%02x ", data[i]);
    }
    printf("\n");
}
extern bool start_timer_flags;
extern int start_timer(int fd, int ms, bool expired);
bool parse_body(packet_info_t *packet)
{
    uint8_t *ptr = packet->body;
    int size = packet->body_len;
    int offset = 0;
    offset = handle_command(packet->head.remoteid, packet->head.localid, ptr, size);


    return true;
}
bool packet_command(packet_info_t *packet)
{

    if (!parse_body(packet))
    {
        return false;
    }
    else
    {
        return true;
    }
}
bool is_compound_packet(uint8_t *data, int len)
{
    uint8_t *pdata = data;
    packet_head_t *head = (packet_head_t *)pdata;
    if (head->packet_len + sizeof(packet_head_t) < len)
    {
        return true;
    }
    return false;
}
bool parse_single_packet(int fd, uint8_t *pdata, int len)
{
    packet_info_t signal_packet;
    packet_head_t *head = (packet_head_t *)pdata;
    if (head->packet_len > MAX_PACKET_SIZE)
    {
        printf("packet len is invalid,packet_len:%d\n", head->packet_len);
        return false;
    }
    if (!checksum_packet(pdata, len))
    {
        printf("packet checksum is error!\n");
        return false;
    }
    signal_packet.head.remoteid = head->remoteid;
    signal_packet.head.packet_len = head->packet_len;
    signal_packet.head.localid = head->localid;
    signal_packet.body = pdata + sizeof(packet_head_t);
    signal_packet.body_len = head->packet_len - 1;
    packet_command(&signal_packet);
}
int split_compound_packet(uint8_t *data, int len)
{
    packet_head_t *head = (packet_head_t *)data;
    return sizeof(packet_head_t) + head->packet_len;
}
bool parse_packet(int fd, uint8_t *data, int len)
{
    uint8_t command[64] = {0};
    // 1.判断是否是复合包
    if (is_compound_packet(data, len))
    {
        int first_len = data[1] + 3;
        if (first_len > 64)
        {
            tcflush(fd, TCIFLUSH);
            send_nak(data[2], data[0]);
            return false;
        }
    }
    else
    {
        parse_single_packet(fd, data, len);
    }

    return true;
}